package middleware

import (
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
)

var casbinService = service.ServiceGroupApp.SystemServiceGroup.CasbinService
var authorityService = service.ServiceGroupApp.SystemServiceGroup.AuthorityService

// CasbinHandler 拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		waitUse, _ := utils.GetClaims(c)
		//获取请求的PATH
		// path := c.Request.URL.Path
		// obj := strings.TrimPrefix(path, global.GVA_CONFIG.System.RouterPrefix)
		// // 获取请求方法
		// act := c.Request.Method
		// // 获取用户的角色
		// sub := strconv.Itoa(int(waitUse.AuthorityId))
		if int(waitUse.AuthorityId) == 1 {
			c.Next()
			return
		}
		// 判断角色是否被禁用
		auth, err := authorityService.GetAuthorityInfo(system.SysAuthority{AuthorityId: uint(waitUse.AuthorityId)})
		if err != nil {
			response.FailWithDetailed(gin.H{}, "获取角色失败", c)
			c.Abort()
			return
		}
		if auth.Enable == 2 {
			response.FailWithDetailed(gin.H{}, "角色已被禁用", c)
			c.Abort()
			return
		}
		// e := casbinService.Casbin() // 判断策略中是否存在
		// success, _ := e.Enforce(sub, obj, act)
		// if !success {
		// 	response.FailWithDetailed(gin.H{}, "权限不足", c)
		// 	c.Abort()
		// 	return
		// }
		c.Next()
	}
}
